package mplayer.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.gson.Gson;

import mplayer.dao.TextService;
import mplayer.entity.Text;

/**
 * Servlet implementation class ManageText
 */
@WebServlet("/ManageText")
public class ManageText extends HttpServlet {
	private static final long serialVersionUID = 1L;
	 Logger logger = LoggerFactory.getLogger(this.getClass());
    private String captureText; 
    private Integer rows = 20;
	private Integer page = 1;
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ManageText() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
	TextService textservice = new TextService();
	
	captureText= request.getParameter("editor1");
	Text tx = new Text(captureText);
	System.out.println(captureText);
	
	if (captureText != null) {
		textservice.SaveText(tx);	
	}
	
	
	try{
		 rows = Integer.parseInt(request.getParameter("rows"));	
	}catch(NumberFormatException e){
		logger.warn("unknown rows limit parameter");
	}			
	
	try{
		page = Integer.parseInt(request.getParameter("page"));	
	}catch(NumberFormatException e){
		logger.warn("unknown parameter : page");
	}
		
	Integer firstResult = rows*page - rows;
	jqGridResponse jsonElement = new jqGridResponse();
	
	
	
	jsonElement.setRows(textservice.getText(rows, firstResult));
	
	float number=  (float) textservice.getResultsCount() / (float) rows;
	Long numberOfpages= (long) Math.ceil(number);	
	
	jsonElement.setTotal(numberOfpages);
	jsonElement.setRecords(textservice.getResultsCount());
    
	PrintWriter out = response.getWriter();
	Gson gson = new Gson();
	response.setContentType("application/json");
	out.print(gson.toJson(jsonElement));
	
	}
}
